package StudyCode.summary.myfile;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class SearchingForFilesByGlobalPattern {
	public static void main(String[] args) throws Exception {
		String glob = "*.jpg";
		Path fileTree = Paths.get("C:/");
		SearchGlobal walk = new SearchGlobal(glob);
		EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);

		Files.walkFileTree(fileTree, opts, Integer.MAX_VALUE, walk);

	}
}

class SearchGlobal implements FileVisitor {

	private final PathMatcher matcher;

	SearchGlobal(String glob) {
		matcher = FileSystems.getDefault().getPathMatcher("glob:" + glob);
	}

	private void search(Path file) throws IOException {
		Path name = file.getFileName();
		if (name != null && matcher.matches(name)) {
			System.out.println("搜索文件找到: " + name + " 在 " + file.toRealPath().toString());
		}
	}

	@Override
	public FileVisitResult postVisitDirectory(Object dir, IOException exc) {
		System.out.println("访问: " + dir);
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) {
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException {
		search((Path) file);
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFileFailed(Object file, IOException exc) {
		return FileVisitResult.CONTINUE;
	}
}
